<?php
namespace catcher\library;

use think\facade\Lang;

class MenuTranslator
{
    protected static array $map = [];

    public static function translate(string $title): string
    {
        $lang = Lang::getLangSet();
        if (!isset(self::$map[$lang])) {
            self::$map[$lang] = self::load($lang);
        }

        if (isset(self::$map[$lang][$title])) {
            return self::$map[$lang][$title];
        }

        $translated = lang($title);
        return $translated ?: $title;
    }

    protected static function load(string $lang): array
    {
        $file = app()->getRootPath() . 'app' . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . 'menus' . DIRECTORY_SEPARATOR . $lang . '.php';
        if (is_file($file)) {
            $tree = include $file;
            return self::flatten($tree);
        }

        return [];
    }

    protected static function flatten(array $tree): array
    {
        $map = [];
        foreach ($tree as $k => $v) {
            if (is_array($v)) {
                if (isset($v['_title'])) {
                    $map[$k] = $v['_title'];
                }
                $map = array_merge($map, self::flatten($v));
            } else {
                $map[$k] = $v;
            }
        }
        return $map;
    }
}